import { create } from "zustand";
import { persist, createJSONStorage } from "zustand/middleware";
import { AppState } from "./types";
import { v4 as uuidv4 } from "uuid";
import {
  API_USER_ENCRYPT,
  API_LOGIN_ENTER,
  API__USER_INFO_LATEST,
} from "@/api/login";
import { encryptParma } from "@/utils";
import { TOKEN_KEY } from "@/config/app.const";
const useAppStore = create<AppState>()(
  persist(
    (set) => ({
      theme: "light",
      user: { logined: false },
      settings: {
        notifications: true,
        guid: uuidv4(),
        appId: "20001",
        ti: "",
        rd: "",
        at: "",
        token: "",
      },
      updateTheme: (theme: "light" | "dark") => set({ theme }),
      updateUser: (user: any) => set({ user }),
      updateSettings: (setting: any) => {
        useAppStore.getState().settings = {
          ...useAppStore.getState().settings,
          ...setting,
        };
      },
      logOut: () => {
        useAppStore.getState().updateUser({ logined: false });
      },
      login: async (formData: any) => {
        const res: any = await API_USER_ENCRYPT();
        if (res.success && res.data) {
          const {
            data: { keyId, publicKey },
          } = res;
          const password = encryptParma(formData.password, publicKey);
          const enterRes: any = await API_LOGIN_ENTER({
            ...formData,
            keyId,
            password,
          });
          if (enterRes.success) {
            console.log("登录");
            useAppStore.getState().afterLoginAction();
          }
        }
      },
      afterLoginAction: async () => {
        const res: any = await API__USER_INFO_LATEST();
        if (res.success && res.data) {
          useAppStore.getState().updateUser({ ...res.data, logined: true });
          console.log(res.data);
        }
      },
    }),
    {
      name: "app-storage", // 存储的键名
      storage: createJSONStorage(() => localStorage), // 自定义存储适配器
      // 排除不需要持久化的字段（如函数）
      partialize: (state) => ({
        theme: state.theme,
        user: state.user,
        settings: state.settings,
      }),
    }
  )
);

export default useAppStore;
